import { StyleSheet, Text, View, ScrollView, TouchableOpacity, Image, Pressable } from 'react-native';
import React, { useEffect, useState } from 'react';
import FastImage from '@d11/react-native-fast-image';
import LinearGradient from 'react-native-linear-gradient';
import { useRoute, useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import { yjhDevices } from '~/utils/deviceMenues';
import { useTranslation } from 'react-i18next';
import { getDeviceDetails } from '~/api/deviceApi';
import { getWuXueCourseApi, getUserDeviceListByDoctor } from '~/api/doctor';
import { FocusAwareStatusBar } from '~/components';
import { isIos, onePx, px2dp, scale, width } from '~/utils/px2dp';
import { observer, webSocketStore } from '~/store';

export default observer(() => {
    const { t } = useTranslation();
    const router: any = useRoute();
    const { device_sn, course_id = '', user_id = '' } = router.params || {};
    const navigation: any = useNavigation();
    const { device_online } = webSocketStore;
    const onPress = (router) => {
        if (device_online == 1) {
            navigation.navigate(router, { device_sn });
        } else {
            Toast.show({ content: t('DoctorDeviceDetailes.t1'), layout: 'top' });
        }
    };
    const [deviceInfo, setDeviceInfo] = useState<any>({});
    const getData = () => {
        getDeviceDetails({ device_sn: device_sn }).then((res) => {
            if (res.status == 1) {
                const data = res.data;
                data.num = data.device_sn.substring(device_sn.length - 3);
                if (yjhDevices.indexOf(data.device_code) == -1) {
                    getWuXueCourse();
                }
                setDeviceInfo(data);
            } else {
                Toast.show({ content: res.msg, layout: 'top' });
            }
        });
    };
    // 获取小包数据
    const [parameterList, setParameterList] = useState([]);
    const getWuXueCourse = () => {
        getWuXueCourseApi({ course_id, id: 0 }).then((res) => {
            setParameterList(res.parameter_list);
        });
    };

    const timesArray = [
        { end_time: '01:00', start_time: '23:00', title: t('Acupoints.t29'), content: t('Acupoints.t30') },
        { end_time: '03:00', start_time: '01:00', title: t('Acupoints.t31'), content: t('Acupoints.t32') },
        { end_time: '05:00', start_time: '03:00', title: t('Acupoints.t33'), content: t('Acupoints.t34') },
        { end_time: '07:00', start_time: '05:00', title: t('Acupoints.t35'), content: t('Acupoints.t36') },
        { end_time: '09:00', start_time: '07:00', title: t('Acupoints.t37'), content: t('Acupoints.t38') },
        { end_time: '11:00', start_time: '09:00', title: t('Acupoints.t39'), content: t('Acupoints.t40') },
        { end_time: '13:00', start_time: '11:00', title: t('Acupoints.t41'), content: t('Acupoints.t42') },
        { end_time: '15:00', start_time: '13:00', title: t('Acupoints.t43'), content: t('Acupoints.t44') },
        { end_time: '17:00', start_time: '15:00', title: t('Acupoints.t45'), content: t('Acupoints.t46') },
        { end_time: '19:00', start_time: '17:00', title: t('Acupoints.t47'), content: t('Acupoints.t48') },
        { end_time: '21:00', start_time: '19:00', title: t('Acupoints.t49'), content: t('Acupoints.t50') },
        { end_time: '23:00', start_time: '21:00', title: t('Acupoints.t51'), content: t('Acupoints.t52') },
    ];
    const getTitleAndContentByTime = (time) => {
        return (
            timesArray.find((item) => {
                const start = item.start_time;
                const end = item.end_time;
                if (start < end) {
                    return time >= start && time < end;
                } else {
                    return time >= start || time < end;
                }
            }) || {}
        );
    };

    // 替换设备
    const replaceDevice = () => {
        navigation.navigate('ReplaceDevice', { device_sn });
    };

    // 查询五穴手表
    const [deviceList, setDeviceList] = useState([]);
    const getWuxueDeviceData = () => {
        getUserDeviceListByDoctor({ user_id }).then((res) => {
            setDeviceList(res.list);
        });
    };
    // 实施睡眠
    const sleeping = () => {
        navigation.navigate('Sleeping', { device_sn: device_sn });
    };
    // 实施测量手指夹
    const fingerScreen = () => {
        navigation.navigate('FingerScreen', { device_sn });
    };

    const reportData = () => {
        if (deviceList.length < 5) {
            Toast.show({ content: t('doctor.t8'), layout: 'top' });
            return;
        }
        const newArray = deviceList.map((item: any, index) => {
            return { course_id: item.course_id, device_id: item.device_id };
        });
        navigation.navigate('DeviceDateView', {
            category: 'acupoint',
            acupointParams: JSON.stringify(newArray),
            type: 'doctor',
            userId: user_id,
        });
    };

    useEffect(() => {
        getData();
        if (user_id) {
            getWuxueDeviceData();
        }
    }, []);
    return (
        <View style={styles.container}>
            <FocusAwareStatusBar translucent />
            <LinearGradient
                style={styles.container}
                colors={['rgba(37, 200, 200, 0.59)', '#fff']}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}>
                <View style={[styles.nav, styles.row]}>
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={() => {
                            navigation.goBack();
                        }}>
                        <Icon name="chevron-back-outline" size={px2dp(50)} color={'#fff'}></Icon>
                    </TouchableOpacity>
                    <Text style={styles.navtitle}>{t('DeviceReadCall.title')}</Text>
                    <View />
                </View>

                <ScrollView contentContainerStyle={styles.contentContainerStyle} showsVerticalScrollIndicator={false}>
                    <View style={styles.deviceInfo}>
                        <Image
                            resizeMode="contain"
                            style={styles.yy01}
                            source={{
                                uri: deviceInfo?.device_image,
                            }}
                        />
                        {yjhDevices.indexOf(deviceInfo.device_code) == -1 && (
                            <Text style={styles.use_course_name}>{deviceInfo?.use_course_name}</Text>
                        )}
                        <Text style={styles.device_sn}>
                            {t('DoctorDeviceDetailes.t2')}：{device_sn}
                        </Text>
                        <View style={styles.bindBt}>
                            <Text style={styles.bt_text}>{t('DoctorDeviceDetailes.t3')}</Text>
                        </View>
                    </View>
                    <View style={styles.card}>
                        <Text style={styles.card_title}>{t('DoctorDeviceDetailes.t4')}</Text>
                        {yjhDevices.indexOf(deviceInfo.device_code) !== -1 ? (
                            <View style={[styles.info]}>
                                <View style={[styles.row]}>
                                    {/* <Pressable style={styles.item} onPress={fingerScreen}>
                                        <View style={styles.imgbox}>
                                            <FastImage
                                                style={styles.icons}
                                                source={{
                                                    uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2023/12/7f344202312151000527061.png',
                                                    priority: FastImage.priority.high,
                                                }}
                                                resizeMode={FastImage.resizeMode.contain}
                                            />
                                        </View>
                                        <Text style={styles.title}>{t('DeviceDetailes.t15')}</Text>
                                    </Pressable>
                                    <Pressable style={styles.item} onPress={sleeping}>
                                        <View style={styles.imgbox}>
                                            <FastImage
                                                style={styles.icons}
                                                source={{
                                                    uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2023/11/de38d20231116104150821.png',
                                                    priority: FastImage.priority.high,
                                                }}
                                                resizeMode={FastImage.resizeMode.contain}
                                            />
                                        </View>
                                        <Text style={styles.title}>{t('DeviceDetailes.t16')}</Text>
                                    </Pressable> */}
                                    <Pressable style={styles.item} onPress={replaceDevice}>
                                        <View style={styles.imgbox}>
                                            <FastImage
                                                style={styles.icons}
                                                source={{
                                                    uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/02/7e152202502281147508257.png',
                                                    priority: FastImage.priority.high,
                                                }}
                                                resizeMode={FastImage.resizeMode.contain}
                                            />
                                        </View>
                                        <Text style={styles.title}>{t('DoctorDeviceDetailes.t5')}</Text>
                                    </Pressable>
                                </View>
                            </View>
                        ) : (
                            <View style={[styles.info, styles.row]}>
                                <TouchableOpacity style={styles.item} onPress={reportData}>
                                    <Image
                                        resizeMode="contain"
                                        style={styles.icons}
                                        source={{
                                            uri: 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/03/60d99202503051449269864.png',
                                        }}
                                    />
                                    <Text style={styles.title}>{t('DoctorDeviceDetailes.t6')}</Text>
                                </TouchableOpacity>
                            </View>
                        )}
                    </View>
                    {parameterList.length > 0 &&
                        Array.isArray(parameterList) &&
                        yjhDevices.indexOf(deviceInfo.device_code) == -1 && (
                            <View style={[styles.card, { backgroundColor: 'none' }]}>
                                <Text style={styles.card_title}>{t('DoctorDeviceDetailes.t7')}</Text>
                                <View style={[styles.courseDetailes, styles.row, styles.between]}>
                                    {parameterList.map((item: any, index) => {
                                        const result: any = getTitleAndContentByTime(item.start_time);
                                        return (
                                            <LinearGradient
                                                key={item?.id}
                                                style={styles.courseCard}
                                                colors={['#FFFFFF', '#E9FAF3']}
                                                start={{ x: 0, y: 0 }}
                                                end={{ x: 0, y: 1 }}>
                                                <View style={[styles.row, styles.between, { marginBottom: px2dp(24) }]}>
                                                    <Text style={styles.time}>{item?.start_time}</Text>
                                                    <Text style={styles.byTimeText}>{result?.content}</Text>
                                                </View>

                                                <View style={[styles.row, styles.between]}>
                                                    <Text style={styles.t3}>
                                                        {t('Acupoints.t20')}:{item?.course_name}
                                                    </Text>
                                                    <View style={[styles.active_border]}>
                                                        <Text style={[styles.active_border_text]}>
                                                            {item?.start_duration}
                                                            {t('Acupoints.t3')}
                                                        </Text>
                                                    </View>
                                                </View>
                                                {item?.course_name2 && (
                                                    <View
                                                        style={[styles.row, styles.between, { marginTop: px2dp(12) }]}>
                                                        <Text style={styles.t3}>
                                                            {t('Acupoints.t21')}:{item?.course_name2}
                                                        </Text>
                                                        <View
                                                            style={[
                                                                styles.active_border,
                                                                { backgroundColor: 'rgba(255, 100, 48, 0.12)' },
                                                            ]}>
                                                            <Text
                                                                style={[
                                                                    styles.active_border_text,
                                                                    { color: '#FF6430' },
                                                                ]}>
                                                                {item?.start_duration2} {t('Acupoints.t3')}
                                                            </Text>
                                                        </View>
                                                    </View>
                                                )}

                                                <View style={styles.line}></View>
                                                <Text style={styles.tips}>{item.desc}</Text>
                                            </LinearGradient>
                                        );
                                    })}
                                </View>
                            </View>
                        )}
                </ScrollView>
            </LinearGradient>
        </View>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    container: {
        flex: 1,
        backgroundColor: '#F7F7F7',
    },
    contentContainerStyle: {
        flexGrow: 1,
        paddingBottom: '30%',
        top: '14%',
    },
    deviceInfo: {
        width: width,
        alignSelf: 'center',
    },
    yy01: {
        width: px2dp(340),
        height: px2dp(340),
        alignSelf: 'center',
    },
    use_course_name: {
        color: '#111111',
        fontSize: scale(30),
        fontWeight: 'bold',
        marginTop: px2dp(24),
        textAlign: 'center',
    },
    device_sn: {
        color: '#111111',
        fontSize: scale(28),
        marginTop: px2dp(24),
        textAlign: 'center',
    },
    bindBt: {
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'rgba(29, 206, 135, 0.12)',
        height: px2dp(80),
        marginTop: px2dp(32),
        borderRadius: px2dp(12),
        width: px2dp(300),
        alignSelf: 'center',
    },
    bt_text: {
        color: '#1DCE87',
        fontSize: scale(28),
        fontWeight: 'bold',
    },
    card: {
        backgroundColor: '#fff',
        padding: px2dp(24),
        marginHorizontal: px2dp(24),
        marginTop: px2dp(32),
        borderRadius: px2dp(24),
    },
    card_title: {
        fontWeight: 'bold',
        fontSize: scale(28),
        color: '#1A1A1A',
    },
    info: {
        marginTop: px2dp(30),
    },
    item: {
        alignItems: 'center',
        justifyContent: 'center',
        width: (width - px2dp(96)) / 5,
    },
    icons: {
        width: px2dp(64),
        height: px2dp(64),
    },
    title: {
        color: '#4C4C4C',
        fontSize: scale(24),
        marginTop: px2dp(12),
        fontWeight: '400',
    },
    nav: {
        position: 'absolute',
        top: isIos() ? '8%' : '6%',
        justifyContent: 'space-between',
        width: width - px2dp(48),
        marginHorizontal: px2dp(24),
        zIndex: 999,
    },
    navtitle: {
        color: '#fff',
        fontSize: scale(30),
        fontWeight: 'bold',
    },
    courseDetailes: {
        flexWrap: 'wrap',
        marginTop: px2dp(12),
    },
    imgbox: {
        width: px2dp(70),
        height: px2dp(70),
        justifyContent: 'center',
        alignItems: 'center',
    },
    courseCard: {
        width: (width - px2dp(56)) / 2,
        backgroundColor: '#fff',
        padding: px2dp(24),
        borderRadius: px2dp(24),
        marginBottom: px2dp(12),
        height: px2dp(330),
        marginHorizontal: px2dp(-24),
    },
    time: {
        color: '#111111',
        fontWeight: '500',
        fontSize: scale(32),
    },
    byTimeText: {
        color: '#111111',
        fontWeight: '500',
        fontSize: scale(28),
    },
    tips: {
        fontWeight: '400',
        color: '#626262',
        fontSize: scale(28),
        lineHeight: px2dp(40),
    },
    t3: {
        fontSize: scale(22),
        color: '#666666',
        width: px2dp(200),
    },
    active_border: {
        backgroundColor: 'rgba(29, 206, 135, 0.12)',
        borderRadius: px2dp(12),
        marginLeft: px2dp(12),
        paddingHorizontal: px2dp(12),
        paddingVertical: px2dp(8),
    },
    active_border_text: {
        color: '#1DCE87',
        fontSize: scale(24),
    },
    line: {
        borderBottomWidth: onePx,
        borderColor: '#eee',
        marginVertical: px2dp(24),
    },
});
